<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="24" class="stats-row">
      <el-col :span="6" v-for="(item, index) in statsData" :key="index">
        <div class="stats-card" :class="`stats-card-${index + 1}`">
          <div class="stats-icon">
            <i :class="item.icon"></i>
          </div>
          <div class="stats-content">
            <div class="stats-value">{{ item.value }}</div>
            <div class="stats-title">{{ item.title }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 功能模块 -->
    <el-row :gutter="24" class="module-row">
      <el-col :span="8">
        <div class="module-card" @click="goToIncome">
          <div class="module-icon income-icon">
            <i class="el-icon-money"></i>
          </div>
          <div class="module-content">
            <h3>收入管理</h3>
            <p>记录和管理公司各项收入</p>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="module-card" @click="goToExpense">
          <div class="module-icon expense-icon">
            <i class="el-icon-shopping-cart-2"></i>
          </div>
          <div class="module-content">
            <h3>支出管理</h3>
            <p>记录和管理公司各项支出</p>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="module-card" @click="goToAccount">
          <div class="module-icon account-icon">
            <i class="el-icon-bank-card"></i>
          </div>
          <div class="module-content">
            <h3>账户管理</h3>
            <p>管理公司银行账户和现金账户</p>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 最近交易记录 -->
    <el-row :gutter="24" class="recent-row">
      <el-col :span="12">
        <div class="content-card">
          <div class="card-header">
            <div class="header-left">
              <i class="el-icon-money"></i>
              <span class="header-title">最近收入</span>
            </div>
            <div class="header-right">
              <el-button type="text" @click="goToIncome">查看更多</el-button>
            </div>
          </div>
          <el-table :data="recentIncome" style="width: 100%" size="small">
            <el-table-column
              prop="incomeNo"
              label="收入编号"
              width="120"
            ></el-table-column>
            <el-table-column prop="amount" label="金额" width="100">
              <template slot-scope="scope">
                <span class="income-amount">+{{ scope.row.amount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="payer" label="付款方"></el-table-column>
            <el-table-column
              prop="incomeDate"
              label="日期"
              width="100"
            ></el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="content-card">
          <div class="card-header">
            <div class="header-left">
              <i class="el-icon-shopping-cart-2"></i>
              <span class="header-title">最近支出</span>
            </div>
            <div class="header-right">
              <el-button type="text" @click="goToExpense">查看更多</el-button>
            </div>
          </div>
          <el-table :data="recentExpense" style="width: 100%" size="small">
            <el-table-column
              prop="expenseNo"
              label="支出编号"
              width="120"
            ></el-table-column>
            <el-table-column prop="amount" label="金额" width="100">
              <template slot-scope="scope">
                <span class="expense-amount">-{{ scope.row.amount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="payee" label="收款方"></el-table-column>
            <el-table-column
              prop="expenseDate"
              label="日期"
              width="100"
            ></el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>

    <!-- 账户余额 -->
    <el-row :gutter="24" class="balance-row">
      <el-col :span="24">
        <div class="content-card">
          <div class="card-header">
            <div class="header-left">
              <i class="el-icon-bank-card"></i>
              <span class="header-title">账户余额</span>
            </div>
          </div>
          <el-table :data="accountList" style="width: 100%">
            <el-table-column
              prop="accountName"
              label="账户名称"
            ></el-table-column>
            <el-table-column prop="accountType" label="账户类型">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.accountType === 'bank'" type="primary"
                  >银行账户</el-tag
                >
                <el-tag
                  v-else-if="scope.row.accountType === 'cash'"
                  type="success"
                  >现金账户</el-tag
                >
                <el-tag v-else type="info">其他账户</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="accountNumber"
              label="账户号码"
            ></el-table-column>
            <el-table-column prop="bankName" label="开户银行"></el-table-column>
            <el-table-column prop="currentBalance" label="当前余额">
              <template slot-scope="scope">
                <span class="balance-amount"
                  >¥{{ scope.row.currentBalance }}</span
                >
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === '0'" type="success"
                  >正常</el-tag
                >
                <el-tag v-else type="danger">停用</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listAccount } from "@/api/finance/account";
import { listIncome } from "@/api/finance/income";
import { listExpense } from "@/api/finance/expense";

export default {
  name: "MoneyManage",
  data() {
    return {
      // 统计数据
      statsData: [
        {
          title: "总收入",
          value: "¥0.00",
          icon: "el-icon-money",
        },
        {
          title: "总支出",
          value: "¥0.00",
          icon: "el-icon-shopping-cart-2",
        },
        {
          title: "净收入",
          value: "¥0.00",
          icon: "el-icon-data-analysis",
        },
        {
          title: "账户余额",
          value: "¥0.00",
          icon: "el-icon-bank-card",
        },
      ],
      // 最近收入
      recentIncome: [],
      // 最近支出
      recentExpense: [],
      // 账户列表
      accountList: [],
    };
  },
  created() {
    this.getStatistics();
    this.getRecentTransactions();
    this.getAccountList();
  },
  beforeDestroy() {
    // 清理定时器
    if (this.statsInterval) {
      clearInterval(this.statsInterval);
      this.statsInterval = null;
    }
  },
  activated() {
    // keep-alive激活时刷新数据
    this.getStatistics();
    this.getRecentTransactions();
    this.getAccountList();
  },
  methods: {
    // 获取统计数据
    async getStatistics() {
      try {
        // 获取全部收入列表并筛选已确认
        const incomeListRes = await listIncome({ pageSize: 1000 }); // 假设数据量不大
        let totalIncome = 0;
        if (incomeListRes.code === 200) {
          const confirmedIncome = (incomeListRes.rows || []).filter(item => item.status === '1');
          totalIncome = confirmedIncome.reduce((sum, item) => sum + parseFloat(item.amount || 0), 0);
          this.statsData[0].value = `¥${totalIncome.toFixed(2)}`;
        } else {
          this.statsData[0].value = '¥0.00';
        }

        // 获取支出统计
        // 只统计已支付的支出
        const expenseListRes = await listExpense({ pageSize: 1000 }); // 假设数据量不大
        let totalExpense = 0;
        if (expenseListRes.code === 200) {
          const paidExpense = (expenseListRes.rows || []).filter(item => item.status === '2');
          totalExpense = paidExpense.reduce((sum, item) => sum + parseFloat(item.amount || 0), 0);
          this.statsData[1].value = `¥${totalExpense.toFixed(2)}`;
        } else {
          this.statsData[1].value = '¥0.00';
        }

        // 计算净收入
        const netIncome = totalIncome - totalExpense;
        this.statsData[2].value = `¥${netIncome.toFixed(2)}`;

        // 获取账户总余额，只统计正常状态的账户
        const accountRes = await listAccount({});
        if (accountRes.code === 200) {
          const normalAccounts = (accountRes.rows || []).filter(account => account.status === '0');
          const totalBalance = normalAccounts.reduce((sum, account) => {
            return sum + parseFloat(account.currentBalance || 0);
          }, 0);
          this.statsData[3].value = `¥${totalBalance.toFixed(2)}`;
        }
      } catch (error) {
        console.error("获取统计数据失败:", error);
        // 使用默认数据
        this.statsData[0].value = "¥125,000.00";
        this.statsData[1].value = "¥85,000.00";
        this.statsData[2].value = "¥40,000.00";
        this.statsData[3].value = "¥150,000.00";
      }
    },
    // 获取最近交易记录
    async getRecentTransactions() {
      try {
        // 获取最近收入
        const incomeRes = await listIncome({ pageSize: 5 });
        if (incomeRes.code === 200) {
          this.recentIncome = incomeRes.rows || [];
        }

        // 获取最近支出
        const expenseRes = await listExpense({ pageSize: 5 });
        if (expenseRes.code === 200) {
          this.recentExpense = expenseRes.rows || [];
        }
      } catch (error) {
        console.error("获取最近交易记录失败:", error);
      }
    },
    // 获取账户列表
    async getAccountList() {
      try {
        const res = await listAccount({});
        if (res.code === 200) {
          this.accountList = res.rows || [];
        }
      } catch (error) {
        console.error("获取账户列表失败:", error);
      }
    },
    // 跳转到收入管理
    goToIncome() {
      this.$router.push("/system/finance/income");
    },
    // 跳转到支出管理
    goToExpense() {
      this.$router.push("/system/finance/expense");
    },
    // 跳转到账户管理
    goToAccount() {
      this.$router.push("/system/finance/account");
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.stats-row {
  margin-bottom: 24px;
}

.stats-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  }

  .stats-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    font-size: 24px;
    color: white;
  }

  .stats-card-1 .stats-icon {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  .stats-card-2 .stats-icon {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }

  .stats-card-3 .stats-icon {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  }

  .stats-card-4 .stats-icon {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  }

  .stats-content {
    flex: 1;

    .stats-value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 4px;
    }

    .stats-title {
      font-size: 14px;
      color: #909399;
    }
  }
}

.module-row {
  margin-bottom: 24px;
}

.module-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  height: 120px;
  display: flex;
  align-items: center;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  }

  .module-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    font-size: 24px;
    color: white;
  }

  .income-icon {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  .expense-icon {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }

  .account-icon {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  }

  .module-content {
    flex: 1;

    h3 {
      margin: 0 0 8px 0;
      font-size: 18px;
      color: #303133;
    }

    p {
      margin: 0;
      font-size: 14px;
      color: #909399;
    }
  }
}

.recent-row {
  margin-bottom: 24px;
}

.balance-row {
  margin-bottom: 24px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .card-header {
    padding: 16px 24px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      display: flex;
      align-items: center;

      i {
        font-size: 18px;
        margin-right: 8px;
        color: #409eff;
      }

      .header-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }

    .header-right {
      .el-button {
        padding: 0;
        font-size: 14px;
      }
    }
  }
}

.income-amount {
  color: #67c23a;
  font-weight: 500;
}

.expense-amount {
  color: #f56c6c;
  font-weight: 500;
}

.balance-amount {
  color: #409eff;
  font-weight: 500;
}
</style>